package com.example.springboottestservice.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxyTest {

    public static void test(){

        TestJDKProxyService testJDKProxyService = new TestJDKProxyServiceImpl();

        TestJDKProxyService proxy = (TestJDKProxyService)JdkProxyFactory.getProxy(testJDKProxyService);

        proxy.proxyMethod("aaa");

    }

}

class JdkProxyFactory {
    public static Object getProxy(Object target) {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(), // 目标类的类加载
                target.getClass().getInterfaces(),  // 代理需要实现的接口，可指定多个
                new TestJDKProxyInvocationHandler(target)   // 代理对象对应的自定义 InvocationHandler
        );
    }
}

interface TestJDKProxyService{
    String proxyMethod(String a);
}

class TestJDKProxyServiceImpl implements TestJDKProxyService{

    @Override
    public String proxyMethod(String a) {
        System.out.println("执行proxyMethod....");
        return a;
    }
}

class TestJDKProxyInvocationHandler implements InvocationHandler {

    private Object target;

    public TestJDKProxyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //调用方法之前，我们可以添加自己的操作
        System.out.println("before method " + method.getName());
        Object result = method.invoke(target, args);
        //调用方法之后，我们同样可以添加自己的操作
        System.out.println("after method " + method.getName());
        return result;
    }
}
